#include <STC15F2K60S2.H>
#include "Tim.h"
#include "Seg.h"
#include "Key.h"
#include "Onewire.h"
#include "stdio.h"
#include "iic.h"
#include "LED.h"
//灯的处理对ucled的值改变的时候频率要很小，灯才会正常，也可能是和数码管同步的影响
//所以再处理灯的时候，不要在数码管子函数里实现，也不要在数码管实现条件和时间下实现
//数码管和灯在同一种条件下都执行会出错，比如都在ucstate==0情况下会相互影响
//所以要避免条件一样的影响：要么一直刷新的时候一直改变ucled的值，要么改变ucled的值后在亮一次
//风扇那个之所以没有错误是因为数码管上面条件没有和改变灯（ueled）值的条件一样
//灯要是一直刷新情况下（无论多少时间间隔）要是和数码管条件一样都出错
//总而言之：就是要在灯亮函数下ucled的值是在赋值的
unsigned long ulms;
unsigned char pucSeg_Buf[9],pucSeg_Code[8],ucSeg_Pos;
unsigned int ucSeg_Dly;
unsigned char ucKey_Dly,ucKey_Old;
unsigned char ucState,ucDac_Flag;
unsigned int uiTemp,ucDac,ucTemp=25;
unsigned char Dat;
unsigned char ucLed;
void Key_Proc(void);
void Seg_Proc(void);
void Temp_Set(unsigned char ucKey_Down);
void Time_Set(void);
void main(){
	Cls_Peripheral() ;
	Timer1Init();
	while(1){
		Key_Proc();
		Seg_Proc();
		Time_Set();
}
}
void Time_1(void) interrupt 3 //定时器1中断函数
{ 
	 ulms++; 
	 if(!(ulms % 1000)) 
	 { 
		 
	} 
	 Led_Disp(ucLed) ;
	 if(++ucSeg_Dly==500) ucSeg_Dly=0;
	 if(++ucKey_Dly==20) ucKey_Dly=0;
	 Seg_Disp(pucSeg_Code, ucSeg_Pos);
	if(++ucSeg_Pos==8) ucSeg_Pos=0;
}
void Key_Proc(void) 
{ 
	 unsigned char ucKey_Val, ucKey_Down, ucKey_Up; 
	 if(ucKey_Dly) return; 
		ucKey_Dly = 1; 
	 ucKey_Val = Key_Read(); 
	 ucKey_Down = ucKey_Val & (ucKey_Old ^ ucKey_Val); 
	 ucKey_Up = ~ucKey_Val & (ucKey_Old ^ ucKey_Val); 
	 ucKey_Old = ucKey_Val; 
	switch(ucKey_Down){
		case 4:
			if(++ucState==3)  ucState=0;
			break;
		case 5:
			ucDac_Flag^=1;
			break;
		case 8:
			Temp_Set(ucKey_Down);
			break;
		case 9:
			Temp_Set(ucKey_Down);
			break;
	}
}
void Seg_Proc(void){
	if(ucSeg_Dly) return;
	ucSeg_Dly=1;
	uiTemp=rd_temperature();
	if(!ucDac_Flag){
		if(ucState!=1){
			if((uiTemp/16)<ucTemp){
			ucDac=0;
			Dat=ucDac*51/100;
		}
		else{
			ucDac=500;
			Dat=ucDac*51/100;
		}
		}
		
	}
	else{
		if((uiTemp/16)<=20){
			ucDac=100;
			Dat=ucDac*51/100;
		}
		else if((uiTemp/16)>=40){
			ucDac=400;
			Dat=ucDac*51/100;
		}
		else{
			ucDac=100+((uiTemp/16.0)*100-2000)*3/20;
			Dat=ucDac*51/100;
		}
	}
	PCF8591_Dac(Dat); 
	switch(ucState){
		case 0:
			sprintf(pucSeg_Buf,"C   %4.2f",uiTemp/16.0);
			break;
		case 1:
			sprintf(pucSeg_Buf,"P     %2d",ucTemp);
			break;
		case 2:
				sprintf(pucSeg_Buf,"A    %3.2f",ucDac/100.0);
			break;
	}
	Seg_Tran(pucSeg_Buf, pucSeg_Code);
}
void Temp_Set(unsigned char ucKey_Down){
	if(ucState==1){
		if(ucKey_Down==9){
			ucTemp++;
		}
		else if(ucKey_Down==8){
			ucTemp--;
		}
	}
}
void Time_Set(void){
	if(!ucDac_Flag){
		ucLed|=0x01;
	}
	else{
		ucLed&=~1;
	}
	switch(ucState){
		case 0:
			ucLed|=2;
			ucLed&=~8;
			break;
		case 1:
			ucLed|=4;
			ucLed&=~2;
			break;
		case 2:
			ucLed|=8;
			ucLed&=~4;
			break;
	}
}